#include <stdlib.h>
#include <string.h>

#include "parse_tree.h"

// 创建一个新的解析树节点
parse_tree_node * new_parse_tree_node(const char * name)
{
    parse_tree_node * new_node = (parse_tree_node *)malloc(sizeof(parse_tree_node));
    if (name)
        strncpy(new_node->name, name, PARSE_TREE_NODE_NAME_MAX);
    else
        new_node->name[0] = '\0';
    new_node->children_num = 0;
    return new_node;
}

// 向父节点添加子节点
int parse_tree_add_child(parse_tree_node * parent, parse_tree_node * child)
{
    if (!parent || !child) return -1;
    parent->children[parent->children_num++] = child;
    return parent->children_num;
}

// 删除解析树节点（递归删除所有子节点）
void del_parse_tree_node(parse_tree_node * node, int recursive)
{
    if (!node) return;

    int i;
    if (recursive) {
        for (i = 0; i < node->children_num; i++) {
            del_parse_tree_node(node->children[i], 1);
        }
    }
    free(node);
}

// 创建一个新的解析树
parse_tree * new_parse_tree()
{
    return (parse_tree *)malloc(sizeof(parse_tree));
}

// 删除解析树
void del_parse_tree(parse_tree * tree)
{
    if (!tree) return;

    if (tree->root) {
        del_parse_tree_node(tree->root, 1);
    }
    free(tree);
}

// 打印解析树节点
void print_parse_tree_node(FILE * fout, parse_tree_node * node, int level)
{
    if (!node) return;

    // print myself
    int i;
    for (i = 0; i < level; i++) {
        fprintf(fout, "|  ");
    }
	//非终结符用+标识，终结符用*标识
    fprintf(fout, ">--%s %s\n", (node->children_num ? "+" : "*"), node->name);

    for (i = 0; i < node->children_num; i++) {
        print_parse_tree_node(fout, node->children[i], level + 1);
    }
}

// 打印解析树
void print_parse_tree(FILE * fout, parse_tree * tree)
{
    if (!fout) return;

    print_parse_tree_node(fout, tree->root, 0);
}